package com.huikeportal.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.huikeportal.controller.common.Lang;
import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.controller.common.Tools;
import com.huikeportal.model.ChangeGcParam;
import com.huikeportal.model.Language;
import com.huikeportal.model.RegionModel;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteCommon;
import com.huikeportal.model.SiteIndex;
import com.huikeportal.model.SiteSimpleInfo;
import com.huikeportal.model.SquareChange;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.IndexPermission;
import com.huikeportal.model.common.PageDataVo;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.CommonService;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.OverViewService;
import com.huikeportal.service.SelectSiteService;

@Controller
public class GateController {

	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;

	@Autowired
	private OverViewService overViewService;

	@Autowired
	private FootfallGlobalService footfallGlobalService;

	@Autowired
	private SelectSiteService selectSiteService;

	@Autowired
	private CommonService commonService;

	@RequestMapping("/gateView")
	public String floorView(String siteId, ModelMap model) throws Exception {
		RegionModel regionModel = new RegionModel();
		if (siteId != null && !"".equals(siteId)) {
			regionModel.setGcSiteId(siteId);
		}
		String sysLang = session.getAttribute("sysLang").toString();
		Language lang = Lang.getInfo(sysLang);
		model.addAttribute("lang", lang);
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		String menuHtml = loginService.getMenuHtml(userInfo, "gateView");
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		// 获取用户信息
		userInfo = loginService.getUserInfo(userInfo);
		// 获取用户根据店铺反查的广场权限
		List<SiteAllInfo> dpGcList = loginService.getDpGcSiteList(userInfo);
		// 获取用户单独广场权限
		List<SiteAllInfo> gcList = loginService.getGcSiteList(userInfo);
		// 获取用户单独店铺权限
		List<SiteAllInfo> jinDpList = loginService.getJinDpSiteList(userInfo);
		// 如果没有权限
		if (dpGcList.size() == 0) {
			return "noPermission";
		}
		// 如果是第一次进来，广场为空
		if (regionModel.getGcSiteId() == null
				|| "".equals(regionModel.getGcSiteId())) {
			// 从session中获取上一次选中的广场，如果没有，从历史表中获取上一次选中的广场，如果没有，则获取第一家广场，并存入历史表，存入session
			if (session.getAttribute("userSiteSession") != null
					&& !"".equals(session.getAttribute("userSiteSession"))) {
				regionModel.setGcSiteId(session.getAttribute("userSiteSession")
						.toString());
			}
			// 如果session中不存在
			else {
				// 从历史表中获取上一次选中的广场
				String lastSiteId = overViewService.getLastSiteId(userInfo,
						"footfallWhole", sysLang);
				// 如果存在
				if (!"".equals(lastSiteId)) {
					// 判断当前场所权限是否存在

					regionModel.setGcSiteId(lastSiteId);
					// 存入session
					session.setAttribute("userSiteSession", lastSiteId);
				}
				// 存入历史表，存入session
				else {
					// 获取第一家广场
					String gcSiteId = "";
					// 如果是从广场权限中选中的广场
					if (gcList.size() != 0) {
						gcSiteId = gcList.get(0).getSiteid();
					}
					// 如果是通过店铺反查选中的广场,sql中需加入店铺范围
					else {
						gcSiteId = dpGcList.get(0).getSiteid();
					}
					regionModel.setGcSiteId(gcSiteId);
					// 存入历史表
					overViewService.insertLastSiteId(userInfo, "footfallWhole",
							gcSiteId, sysLang);
					// 存入session
					session.setAttribute("userSiteSession", gcSiteId);
				}
			}
		} else {
			// 更新历史表
			overViewService.updateLastSiteId(userInfo, "footfallWhole",
					regionModel.getGcSiteId(), sysLang);
			// 更新session
			session.setAttribute("userSiteSession", regionModel.getGcSiteId());
		}
		/** 如果广场不是有权限的广场，则加入店铺过滤器 **/
		if (!Tools.isHaveGcPer(gcList, regionModel.getGcSiteId())) {
			regionModel.setDpString(Tools.pinjieId(jinDpList));
		}
		/** 更换广场初始化 **/
		// 初始化默认广场信息
		SiteCommon siteCommon = selectSiteService.querySiteInfo(regionModel
				.getGcSiteId());
		model.addAttribute("siteCommon", siteCommon);
		// 更换广场div初始化数据
		ChangeGcParam changeGcParam = new ChangeGcParam();
		changeGcParam.setSelectType("0");// 单选广场
		changeGcParam.setGcString(siteCommon.getSiteId());// 已经选择的广场id
		List<SiteAllInfo> yuanGcList = loginService.getGcSiteList(userInfo);
		SquareChange squareChange = selectSiteService.squareChangeLoad(
				changeGcParam, dpGcList, yuanGcList);// 获取初始化更换广场信息
		model.addAttribute("squareChange", squareChange);
		model.addAttribute("selectType", changeGcParam.getSelectType());
		model.addAttribute("backPage", "gateView");
		/** 更换广场初始化 **/
		// 拼接下拉框
		List<SiteAllInfo> leftList = new ArrayList<SiteAllInfo>();
		List<SiteSimpleInfo> rightGcList = new ArrayList<SiteSimpleInfo>();
		List<SiteSimpleInfo> rightQyList = new ArrayList<SiteSimpleInfo>();
		List<SiteSimpleInfo> rightLcList = new ArrayList<SiteSimpleInfo>();
		List<SiteSimpleInfo> rightDpList = new ArrayList<SiteSimpleInfo>();
		SiteAllInfo site = new SiteAllInfo();
		List<SiteSimpleInfo> gcLcList = overViewService.getComboResult(
				regionModel, "12", userInfo);
		List<SiteSimpleInfo> qyLcList = overViewService.getComboResult(
				regionModel, "13", userInfo);
		List<SiteSimpleInfo> lcLcList = overViewService.getComboResult(
				regionModel, "14", userInfo);
		List<SiteSimpleInfo> dpLcList = overViewService.getComboResult(
				regionModel, "15", userInfo);
		if (gcLcList.size() != 0) {
			site = new SiteAllInfo();
			site.setSiteid("300");
			site.setSitename(lang.getSquare());
			leftList.add(site);
			rightGcList = gcLcList;
		}
		if (qyLcList.size() != 0) {
			site = new SiteAllInfo();
			site.setSiteid("400");
			site.setSitename(lang.getDomain());
			leftList.add(site);
			rightQyList = qyLcList;
		}
		if (lcLcList.size() != 0) {
			site = new SiteAllInfo();
			site.setSiteid("500");
			site.setSitename(lang.getFloor());
			leftList.add(site);
			rightLcList = lcLcList;
		}
		if (dpLcList.size() != 0) {
			site = new SiteAllInfo();
			site.setSiteid("600");
			site.setSitename(lang.getStore());
			leftList.add(site);
			rightDpList = dpLcList;
		}
		model.addAttribute("leftList", leftList);
		model.addAttribute("rightGcList", JSONArray.fromObject(rightGcList)
				.toString());
		model.addAttribute("rightQyList", JSONArray.fromObject(rightQyList)
				.toString());
		model.addAttribute("rightLcList", JSONArray.fromObject(rightLcList)
				.toString());
		model.addAttribute("rightDpList", JSONArray.fromObject(rightDpList)
				.toString());
		// 获取用户指标权限
		List<String> indexList = footfallGlobalService.getUserIndex(userInfo);
		IndexPermission index = Tools.initIndex(indexList, sysLang);
		model.addAttribute("indexList", index);// 用于标题栏动态显示
		model.addAttribute("index", JSONArray.fromObject(index).toString());
		// 获取用户按钮权限
		// 查询当前页面id
		SqlParameter sql = new SqlParameter();
		sql.setSysLang(sysLang);
		sql.setString("gateView");
		Integer menuId = selectSiteService.getMenuId(sql);
		// 获取用户权限按钮信息
		List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
				userInfo.getUserId(), menuId);
		String isHaveExport = "0";
		for (int i = 0; i < buttonList.size(); i++) {
			if ("8".equals(buttonList.get(i).getDicCode())) {
				isHaveExport = "1";
				break;
			}
		}
		model.addAttribute("isHaveExport", isHaveExport);
		return "gateOverview";
	}

	/**
	 * 根据场所id查询场所指标
	 * 
	 * @param qyList
	 * @param regionModel
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private List<SiteIndex> pinjieIndex(List lcList, RegionModel regionModel,
			UserInfo userInfo) throws Exception {
		List<SiteIndex> siteIndexList = new ArrayList<SiteIndex>();
		// 循环区域列表，计算每一个指标
		for (int i = 0; i < lcList.size(); i++) {
			SiteAllInfo qySite = (SiteAllInfo) lcList.get(i);
			SiteIndex siteIndex = new SiteIndex();
			siteIndex.setSiteId(qySite.getSiteid());
			siteIndex.setSiteName(qySite.getSitename());
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("timeType", regionModel.getTimeType());// 设置当天最近7、14天等
			map.put("timeType_table", regionModel.getDateType());// 设置日周月年
			map.put("startDate", regionModel.getStartDate());// 设置自己选中的开始日期
			map.put("endDate", regionModel.getEndDate());// 设置自己选中的结束日期
			map.put("siteId", qySite.getSiteid());// 设置场所id
			map.put("userInfo", userInfo);// 设置当前用户
			List<ReportGraphData> dataList = footfallGlobalService
					.getGraphData(map);
			siteIndex = Tools.mathIndex(dataList, siteIndex);
			siteIndexList.add(siteIndex);
		}
		return siteIndexList;
	}

	/**
	 * ajax查询楼层概览
	 * 
	 * @param siteType
	 * @param siteId
	 * @param lcName
	 * @param lcDate
	 * @param lcTime
	 * @param startDate
	 * @param endDate
	 * @param currentPage
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getTdView")
	@ResponseBody
	public Map<String, Object> getTdView(String siteType, String siteId,
			String tdName, String tdDate, String tdTime, String startDate,
			String endDate, String currentPage) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		RegionModel regionModel = initRegion(siteType, siteId, tdName, tdDate,
				tdTime, startDate, endDate);
		PageDataVo pageDataVo = new PageDataVo();
		// 根据广场查询首页区域(分页查询)
		if (currentPage == null || "".equals(currentPage)) {
			pageDataVo.setCurrentPage(1);
		} else {
			pageDataVo.setCurrentPage(Integer.parseInt(currentPage));
		}
		// 获取每页显示条数
		pageDataVo.setPageSize(Integer.parseInt(MessageManager
				.getMsg("viewPageSize")));
		// 设置开始行数
		pageDataVo.setStartRow((pageDataVo.getCurrentPage() - 1)
				* pageDataVo.getPageSize());
		pageDataVo.setSearchParameter(regionModel);
		// 分页查询通道
		pageDataVo = overViewService.getTdList(pageDataVo);
		// 根据通道查询指标信息
		List<SiteIndex> indexList = pinjieIndex(pageDataVo.getPageResult(),
				regionModel, userInfo);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("indexList", indexList);
		/*** 动态获取指标，2015年12月4日15:47:12 **/
		// 获取用户指标权限
		String sysLang = session.getAttribute("sysLang").toString();
		userInfo = loginService.getUserInfo(userInfo);
		List<String> indexL = footfallGlobalService.getUserIndex(userInfo);
		// 1_5代表概览模块，700代表通道
		String dateType = "";
		// 时
		if ("hour".equals(tdDate)) {
			dateType = "1";
		}
		// 日
		else if ("day".equals(tdDate)) {
			dateType = "2";
		}
		// 周
		else if ("week".equals(tdDate)) {
			dateType = "3";
		}
		// 月
		else if ("month".equals(tdDate)) {
			dateType = "4";
		}
		// 年
		else if ("year".equals(tdDate)) {
			dateType = "5";
		}
		indexL = commonService.getIndexList(indexL, "1_5", "700", dateType);
		IndexPermission index = Tools.initIndex(indexL, sysLang);
		map.put("index", index);
		/*** 动态获取指标，2015年12月4日15:47:12 end **/
		// 设置分页参数
		map.put("currentPage", pageDataVo.getCurrentPage());
		map.put("maxPage", pageDataVo.getMaxPage());
		return map;
	}

	/**
	 * 初始化查询区域参数信息
	 * 
	 * @param siteType
	 * @param siteId
	 * @param qyName
	 * @param qyDate
	 * @param qyTime
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws Exception
	 */
	private RegionModel initRegion(String siteType, String siteId,
			String tdName, String tdDate, String tdTime, String startDate,
			String endDate) throws Exception {
		RegionModel regionModel = new RegionModel();
		if ("300".equals(siteType)) {
			regionModel.setGcSiteId(siteId);
		} else if ("400".equals(siteType)) {
			regionModel.setQySiteId(siteId);
		} else if ("500".equals(siteType)) {
			regionModel.setLcSiteId(siteId);
		} else if ("600".equals(siteType)) {
			regionModel.setDpSiteId(siteId);
		}
		if (tdName != null && !"".equals(tdName)) {
			regionModel.setTdSiteName(URLDecoder.decode(tdName, "UTF-8"));
		}
		regionModel.setDateType(tdDate);
		regionModel.setTimeType(tdTime);
		if (startDate != null && !"".equals(startDate)) {
			regionModel.setStartDate(startDate);
		}
		if (endDate != null && !"".equals(endDate)) {
			regionModel.setEndDate(endDate);
		}
		return regionModel;
	}
}
